package cheme.ProcessEditor.DirectEdit;

import java.text.MessageFormat;

import org.eclipse.jface.util.Assert;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.widgets.Composite;

public class ChemeNumericCellEditor  extends ChemeTextCellEditor
{
	public ChemeNumericCellEditor()
	{
		super();
	}
	
	/**
	 * @param parent
	 */
	public ChemeNumericCellEditor(Composite parent)
	{
		super(parent);
	}
	
	/**
	 * @param parent
	 * @param style
	 */
	public ChemeNumericCellEditor(Composite parent, int style)
	{
		super(parent, style);
	}
	
	@Override
	protected boolean isCorrect(Object value)
	{
		setErrorMessage(null);
		
		if(((String)value).isEmpty())
		{
			return true;
		}
		
		try
		{
			double test = Double.parseDouble((String)value);
		}
		catch(Exception e)
		{
			return false;
		}

		if(getValidator() == null)
		{
			return true;
		}

		String errorMessage = getValidator().isValid(value);

		if(null != errorMessage && !(errorMessage.isEmpty()))
		{
			setErrorMessage(errorMessage);
		}

		// return (getErrorMessage() == null || getErrorMessage().equals(""));//$NON-NLS-1$

		return true;
	}
	
	String lastValidText = "";
	
	protected void editOccured(ModifyEvent e)
	{
        String value = text.getText();
        
        if (value == null)
        {
			value = "";//$NON-NLS-1$
		}
        
        Object typedValue = value;
        boolean oldValidState = isValueValid();
        boolean newValidState = isCorrect(typedValue);
        
        if (typedValue == null && newValidState)
        {
			Assert.isTrue(false, "Validator isn't limiting the cell editor's type range");//$NON-NLS-1$
		}
        
        if (!newValidState)
        {
        	value = lastValidText;
        	
            // try to insert the current value into the error message.
            //setErrorMessage(MessageFormat.format(getErrorMessage(), new Object[] { value }));
        }
        else
        {
        	lastValidText = value;
        }
        
        valueChanged(oldValidState, newValidState);
    }
}
